package com.loto.insurance.oem.web.utils;

import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.servlet.http.HttpServletRequest;

import com.loto.insurance.oem.web.enumeration.ConfigFileEnum;
import com.loto.utils.XML;

public class Config {
  @SuppressWarnings("unchecked")
  public static <T> T getConfigFile(HttpServletRequest request,
	  ConfigFileEnum fileEnum, final Class<T> tclass) {
	try {
	  EhcacheUtil ehcache = EhcacheUtil.getInstance();
	  Object o = ehcache.get("configFileCache", fileEnum.toString());
	  if (o != null) {
		return (T) o;
	  }
	  String fileName = request.getSession().getServletContext()
		  .getRealPath("/")
		  + fileEnum.toString();
	  T config = XML.fromXMLFile(fileName, tclass);
	  ehcache.put("configFileCache", fileEnum.toString(), config);
	  return config;
	} catch (Exception e) {
	  e.printStackTrace();
	}
	return null;
  }

  @SuppressWarnings("unchecked")
  public <T> T getConfigFile(ConfigFileEnum fileEnum, final Class<T> tclass) {
	try {
	  String path = this.getClass().getResource("").getPath()
		  .replaceAll("%20", " ");
	  String fileName = path.substring(0, path.indexOf("WEB-INF"))
		  + fileEnum.toString();
	  EhcacheUtil ehcache = EhcacheUtil.getInstance();
	  Object o = ehcache.get("configFileCache", fileEnum.toString());
	  if (o != null) {
		return (T) o;
	  }
	  T config = XML.fromXMLFile(fileName, tclass);
	  ehcache.put("configFileCache", fileEnum.toString(), config);
	  return config;
	} catch (Exception e) {
	  e.printStackTrace();
	}
	return null;
  }

  public static <T> boolean updateConfigFile(HttpServletRequest request,
	  ConfigFileEnum fileEnum, final T t, final Class<T> tclass) {
	boolean isOk = false;
	try {
	  EhcacheUtil ehcache = EhcacheUtil.getInstance();
	  ehcache.remove("configFileCache", fileEnum.toString());
	  String fileName = request.getSession().getServletContext()
		  .getRealPath("/")
		  + fileEnum.toString();
	  isOk = XML.toXMLFile(t, tclass, fileName);
	} catch (Exception e) {
	  e.printStackTrace();
	}
	return isOk;
  }

  public static boolean updatePropertiesFile(HttpServletRequest request,
	  ConfigFileEnum fileEnum, final String content) {
	boolean isOk = false;
	FileWriter fw = null;
	try {
	  String fileName = request.getSession().getServletContext()
		  .getRealPath("/")
		  + fileEnum.toString();
	  fw = new FileWriter(fileName);
	  fw.write(content, 0, content.length());
	  fw.flush();
	  fw.close();
	  isOk = true;
	} catch (Exception e) {
	  e.printStackTrace();
	}
	return isOk;
  }
}
